#include "MyTime.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

bool MyTime::is_time_format(const char* string)
{
	int cntd = 0, cntm = 0;
	for (int i = 0; string[i] != '\0'; ++i)
	{
		if (i > 8) return false;
		if (isdigit(string[i]))
		{
			cntd++;
		}
		else if (string[i] == ':')
		{
			if (cntd > 2 || cntd == 0) return false;
			cntd = 0;
			cntm++;
		}
	}
	if (cntm == 2)
		return true;
	return false;
}

bool MyTime::is_day_time(const char* string)
{
	if (!is_time_format(string)) return false;
	int _hour, _min, _sec;
	sscanf_s(string, "%d:%d:%d", &_hour, &_min, &_sec);
	if (_hour < 0 || _hour >= 24 ||
		_min < 0 || _min >= 60 ||
		_sec < 0 || _sec >= 60)
	{
		return false;
	}
	else
	{
		return true;
	}
}

MyTime::MyTime()
{
	time_t t = time(nullptr);
	struct tm local;
	localtime_s(&local, &t);
	seconds = local.tm_hour * 3600 + local.tm_min * 60 + local.tm_sec;
}

MyTime::MyTime(int h, int m, int s)
{
	seconds = h * 3600 + m * 60 + s;
}

MyTime::MyTime(int seconds)
{
	if (seconds >= 86400)
		seconds %= 86400;
	this->seconds = seconds;
}

MyTime::MyTime(const char* string)
{
	int _hour, _min, _sec;
	sscanf_s(string, "%d:%d:%d", &_hour, &_min, &_sec);
	seconds = _hour * 3600 + _min * 60 + _sec;
}

int MyTime::hour()
{
	return seconds / 3600;
}

int MyTime::min()
{
	return (seconds % 3600) / 60;
}

int MyTime::sec()
{
	return seconds % 60;
}

bool MyTime::operator==(time_t time)
{
	struct tm local;
	localtime_s(&local, &time);
	return local.tm_hour == this->hour() && local.tm_min == this->min() && local.tm_sec == this->sec();
}

void MyTime::operator+=(const MyTime& rhs)
{
	*this = *this + rhs;
}

MyTime MyTime::operator+(const MyTime& rhs)
{
	return MyTime(this->seconds + rhs.seconds);
}

MyTime MyTime::operator-(const MyTime& rhs)
{
	return MyTime(this->seconds - rhs.seconds);
}

bool MyTime::operator>(const MyTime& rhs)
{
	return seconds > rhs.seconds;
}

bool MyTime::operator<(const MyTime& rhs)
{
	return seconds < rhs.seconds;
}

bool MyTime::between(MyTime& start, const MyTime& elapsed)
{
	return seconds >= start.seconds&& seconds <= (start + elapsed).seconds;
}

void MyTime::print_status()
{
	printf("%d:%d:%d", hour(), min(), sec());
}

char* MyTime::gen_str()
{
	char* buffer = new char[10];
	sprintf_s(buffer, 10, "%d:%d:%d", hour(), min(), sec());
	return buffer;
}

std::unique_ptr<char[]> MyTime::gen_str_cpp11()
{
	std::unique_ptr<char[]> buffer(new char[20]);
	sprintf_s(buffer.get(), 20, "%d:%d:%d", hour(), min(), sec());
	return buffer;
}
